package cn.geminis.everydata.service.controller;

import cn.geminis.core.data.query.QueryParameters;
import cn.geminis.core.data.query.QueryService;
import cn.geminis.everydata.service.entity.Category;
import cn.geminis.everydata.service.model.CategoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Allen
 */
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryRepository repository;

    @PostMapping
    public Page<Category> findPage(@RequestBody final QueryParameters queryParameters) {
        return this.repository.findPage(queryParameters);
    }

    @GetMapping("/{id}")
    public Category get(@PathVariable("id") String id) {
        return repository.where("id", id).findOne().get();
    }

    @PutMapping
    public void save(@RequestBody Category category) {
        this.repository.save(category);
    }

    @DeleteMapping
    public void delete(@RequestBody List<String> pathIds) {
        pathIds.forEach(id -> this.repository.deleteByPathId(id + "%"));
    }

    @RequestMapping(value = {"/children/", "/children/{parentId}"}, method = RequestMethod.GET)
    public List<Category> children(@PathVariable(required = false) String parentId) {
        QueryService repo = repository;
        if (StringUtils.isEmpty(parentId)) {
            repo = repo.where("parentId", "is null", "null");
        } else {
            repo = repo.where("parentId", parentId);
        }
        return repo.findList();
    }

}
